/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.sunspotworld;

import com.sun.spot.io.j2me.radiogram.Radiogram;
import com.sun.spot.io.j2me.radiogram.RadiogramConnection;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.swing.JOptionPane;

/**
 *
 * @author Salaver
 */
public class HiloSensoresExternos extends Thread{
    
    public boolean corriendo = true;
    private static final int HOST_PORT_2 = 68;
    private static final int HOST_PORT = 67;
    RadiogramConnection rConR = null;
    Datagram dgR = null;
    RadiogramConnection rConE = null;
    Datagram dgE = null;
    ConexionBD con = new ConexionBD();
    
    public void cosechando(){
        try {
            rConR = (RadiogramConnection) Connector.open("radiogram://:" + HOST_PORT);
            
            while (corriendo){
                    if (HidroponiaHost.cosecha.etapa.getId()>1){
                        sensoresExternos();
                    }
                    Thread.sleep(1000);
                }
             
        } catch (InterruptedException ex) {
                Logger.getLogger(HiloSensoresExternos.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(HiloSensoresExternos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void transmitir(int tipoSpot, int pin, int action){
        try {
            // Open up a broadcast connection to the host port
            // where the 'on Desktop' portion of this demo is listening
            rConE = (RadiogramConnection) Connector.open("radiogram://broadcast:" + HOST_PORT_2);
            dgE = rConE.newDatagram(50);  // only sending 12 bytes of data
            dgE.reset();
            dgE.writeInt(tipoSpot);
            dgE.writeInt(pin);
            dgE.writeInt(action);
            rConE.send(dgE);
        } catch (Exception e) {
            System.err.println("Caught " + e + " in connection initialization.");
        }
    } 
    
        
    public void sensoresExternos(){
         try {
            dgR = (Radiogram)rConR.newDatagram(rConR.getMaximumLength());
            if (rConR.packetsAvailable() == true){
            rConR.receive(dgR);
            long tiempo = dgR.readLong();
            int val = dgR.readInt();
            int tipo = dgR.readInt();
            System.out.println("recibi valor: "+val+" sensor "+tipo);
            con.conectar();
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            SimpleDateFormat sdf2 = new SimpleDateFormat("mm:ss");
            //actualizar reloj
            if (("20:00".equals(sdf2.format(now))) || ("40:00".equals(sdf2.format(now))) || ("00:00".equals(sdf2.format(now)))){
                String query1 = "INSERT INTO medidor_mezcla VALUES("+tipo+","+HidroponiaHost.cosecha.mezcla.getId()+",'"+sdf.format(now)+"',"+val+")";
                con.insertar(query1);
                if ((tipo == 1) && (val<300)){
                    HidroponiaHost.hiloS.transmitir(3,1,1);
                } else if ((tipo == 1) && (val>=300)){
                    HidroponiaHost.hiloS.transmitir(3,1,0);
                }
            }
            if (tipo == 1){
                HidroponiaHost.dialesL.setValor(val);
            } else{
                HidroponiaHost.dialesT.setValor(val);
            }
            con.desconectar();
            }
        } catch (Exception e) {
             System.err.println("Receive caught " + e.getMessage());
        }
    }
    
    public void terminarCosecha(){
        this.corriendo = false;
    }
   
    public void run(){
        try {
            System.out.println("comienzo de externos");
            Thread.sleep(5000);
            cosechando();
        } catch (InterruptedException ex) {
            Logger.getLogger(HiloSensoresExternos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
